<?php
namespace App\Modules\Order\Jobs;

use App\Modules\Free\Models\FreeRecord;
use App\Modules\Order\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class FreeJob implements ShouldQueue
{
    use Queueable,SerializesModels;

    public $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->handle();//队列方法，正式上线需要注释掉
    }

    public function handle()
    {
        if ($this->order->type == Order::TYPE_PACKAGE && $this->order->detail['is_free']) {
            FreeRecord::query()
                ->create([
                    "shop_id" => $this->order->shop_id,
                    "title" => $this->order->title,
                    "user_id" => $this->order->user_id,
                    "cover" => $this->order->deatil['order_cover'],
                    "order_id" => $this->order->id,
                    "good_type" => Order::TYPE_PACKAGE,
                    "good_id" => $this->order->link_id,
                    "aim" => $this->order->price,
                    "unlocked" => 0,
                ]);
        } elseif ($this->order->type == Order::TYPE_GOOD) {

            foreach ($this->order->detail as $item) {
                if ($item['is_free']) {
                    FreeRecord::query()
                        ->create([
                            "shop_id" => $this->order->shop_id,
                            "title" => $item['good_name'],
                            "user_id" => $this->order->user_id,
                            "order_id" => $this->order->id,
                            "good_type" => Order::TYPE_GOOD,
                            "good_id" => $item['good_id'],
                            "cover" =>$item['order_cover'],
                            "aim" => $item['price'] * $item['number'],
                            "unlocked" => 0,
                        ]);
                }
            }
        }
    }
}
